package cn.wizzer.app.web.modules.controllers.platform.user;

import cn.wizzer.app.sys.modules.services.SysMsgService;
import cn.wizzer.app.user.modules.models.vo.SysMsgVo;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.framework.base.Result;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import javax.servlet.http.HttpServletRequest;

@IocBean
@At("/platform/user/msg")
public class MsgController {
    private static final Log log = Logs.get();

    @Inject
    @Reference
    private SysMsgService userMsgService;

    @Inject
    @Reference
    private UserService userService;

    @At({"/", "/list/?"})
    @Ok("beetl:/platform/user/msg/index.html")
    @RequiresPermissions("user.msg.list")
    public void index(String type, HttpServletRequest req) {
        if (Strings.isBlank(type)) {
            type = "all";
        } else {
            type = "system".equals(type) ? "0" : "1";
        }
        req.setAttribute("type", type);
    }


    /**
     * 消息列表
     * @param searchType String 类型（系统消息、用户消息、全部）
     * @param pageNumber int
     * @param pageSize int
     * @return Object
     */
    @At
    @Ok("json:full")
    @RequiresPermissions("user.msg.list")
    public Object data(@Param("searchType") String searchType, @Param("pageNumber") int pageNumber, @Param("pageSize") int pageSize) {
        try {
            // select us.*,u.nickName from user_msg us left join user u on us.userId = u.id;
            Sql sql = Sqls.create("select us.*,u.nickName,u.phone from user_msg us ");
            Sql countSql = Sqls.create("select count(1) from user_msg us ");
            Sql joinSql = Sqls.create("left join user u on us.userId = u.id " +
                    "$condition ");
            Cnd cnd = Cnd.NEW();
            if (Strings.isNotBlank(searchType) && !"all".equals(searchType)) {
                cnd.and("type", "=", searchType);
            }
            joinSql.setCondition(cnd);
            sql.appendSourceSql(joinSql.toString());
            sql.appendSourceSql("order by sendAt desc ");
            countSql.appendSourceSql(joinSql.toString());
            return Result.success().addData(userService.listPage(SysMsgVo.class, pageNumber, pageSize, sql.toString(), countSql.toString()));
        } catch (Exception e) {
            return Result.error();
        }
    }


    /**
     * 发送消息
     * @param nutMap NutMap
     * @return Object
     */
    @At("/add")
    @Ok("json")
    @RequiresPermissions("user.msg.add")
    public Object add(@Param("..") NutMap nutMap) {
        try {
//            UserMsg userMsg = nutMap.getAs("msg", UserMsg.class); // 获取消息属性
//            userMsg.setSendAt(Times.getTS());
//            userMsg.setOpBy(StringUtil.getPlatformUid());
//            if ("1".equals(userMsg.getType())) {
//                String[] userIds = StringUtils.split(nutMap.getString("users", ""), ","); // 分割id
//                userMsgService.saveUserTypeMsg(userMsg, userIds);
//            } else {
//                userMsgService.insert(userMsg);
//            }

            return Result.success();
        } catch (Exception e) {
            return Result.error();
        }
    }


    /**
     * 删除消息
     * @param id String
     * @return Object
     */
    @At("/delete/?")
    @Ok("json")
    @RequiresPermissions("user.msg.delete")
    public Object delete(@Param("id") String id) {
        try {
            userMsgService.vDelete(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }


    /**
     * 查询消息
     * @param id String
     * @return Object
     */
    @At("/edit/?")
    @Ok("json")
    @RequiresPermissions("user.msg.edit")
    public Object edit(@Param("id") String id) {
        try {
            return Result.success();
        } catch (Exception e) {
            return Result.error();
        }
    }


    /**
     * 编辑消息
     * @param nutMap NutMap
     * @return Object
     */
    @At("/editDo")
    @Ok("json")
    @RequiresPermissions("user.msg.edit")
    public Object editDo(@Param("..") NutMap nutMap) {
        try {
//            UserMsg userMsg = nutMap.getAs("msg", UserMsg.class);
//            userMsgService.update(userMsg);
            return Result.success();
        } catch (Exception e) {
            return Result.error();
        }
    }



    /**
     * 查询用户列表
     * @param userType Integer 用户类型
     * @param searchKeyword String 搜索关键字
     * @param pageNumber int
     * @param pageSize int
     * @return Object
     */
    @At
    @Ok("json:{locked:'password|salt',ignoreNull:false}")
    @RequiresPermissions("user.manager.list")
    public Object user_list(@Param("userType") Integer userType, @Param("searchKeyword") String searchKeyword, @Param("pageNumber") int pageNumber, @Param("pageSize") int pageSize) {
        try {
            return Result.success().addData(userService.userList(userType, null, searchKeyword, null , null, null, pageNumber, pageSize));
        } catch (Exception e) {
            return Result.error();
        }
    }
    /**
     * 查询代理列表
     * @param searchKeyword String 搜索关键字
     * @param pageNumber int
     * @param pageSize int
     * @return Object
     */
    @At
    @Ok("json:{locked:'password|salt',ignoreNull:false}")
    @RequiresPermissions("user.manager.list")
    public Object agent_list( @Param("searchKeyword") String searchKeyword, @Param("pageNumber") int pageNumber, @Param("pageSize") int pageSize) {
        try {
            return Result.success().addData(userService.userList(null,1, searchKeyword, null , null, null, pageNumber, pageSize));
        } catch (Exception e) {
            return Result.error();
        }
    }

}
